package main

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"gitee.com/zhenxinma/gocommon/pkg/xserver/authserver"

	authsvr "gitee.com/zhenixnma/blogsvr/internal/server/authserver"

	"gitee.com/zhenixnma/blogsvr/internal/server"

	"github.com/gin-gonic/gin"
)

// TODO: 优雅退出.

type app struct {
	apiSvr *http.Server
	cancel context.CancelFunc
	close  chan error
}

// init 初始化svr.
func (a *app) init(ctx context.Context) {
	fmt.Println("start init")
	server.InitRpcServer()
	// TODO: 测试.
	resp := &authserver.AuthResponse{}
	if err := authsvr.GetAuthServerImplInstance().GetAuthInfo(context.Background(),
		&authserver.AuthArgs{UserID: "zhenxinma123"}, resp); err != nil {
		fmt.Printf("authsvr response:[%+v]\n", resp)
	}
	d, _ := json.Marshal(resp)
	fmt.Printf("blogsvr call authsver response:[%+v]\n", string(d))
}

// run 运行svr.
func (a *app) run(ctx context.Context) {

	// 监听指定信号：ctrl+c以及kill.
	sigs := make(chan os.Signal, 1)
	signal.Notify(sigs, syscall.SIGHUP, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGKILL, syscall.SIGTERM)
	go func() {
		select {
		case r := <-sigs:
			a.close <- fmt.Errorf("syscall:[%+v]\n", r)
		}
	}()
	if err := a.apiSvr.ListenAndServe(); err != nil {
		a.close <- err
	}
}

func (a *app) quit() {
	select {
	case err := <-a.close:
		fmt.Println("svr done because err:" + err.Error())
	}
}

func main() {

	ctx, cancel := context.WithCancel(context.Background())
	r := gin.New()
	r.GET("/test", func(c *gin.Context) {
		c.JSON(http.StatusOK, "hello word")
	})
	app := &app{
		apiSvr: &http.Server{
			Addr:              ":9999",
			Handler:           r,
			ReadHeaderTimeout: 5 * time.Second,
			WriteTimeout:      5 * time.Second,
		},
		cancel: cancel,
		close:  make(chan error, 1), // 容量为1不阻塞.
	}

	go func() {
		app.init(ctx)
		//app.run(ctx)
	}()
	app.quit()
}
